package handler

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/share309/gojwt"
	"net/http"
	"time"
	"user_5.24/api/request"
	"user_5.24/consts"
	"user_5.24/internal/dao"
	"user_5.24/internal/model"
)

func Ping(c *gin.Context) {
	c.JSON(200, gin.H{
		"message": "pong",
	})
}

func Register(c *gin.Context) {
	var req request.Register
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile}, &user)

	if user.Id > 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "用户已存在",
			"data": false,
		})
		return
	}
	result := dao.Create(&model.User{
		Mobile:   req.Mobile,
		Password: req.Password,
	})
	if !result {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "注册失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "注册成功",
		"data": true,
	})

}

func Login(c *gin.Context) {
	var req request.Login
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var user model.User
	dao.GetOneByFields(&model.User{Mobile: req.Mobile, Password: req.Password}, &user)
	if user.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "账号或者密码错误",
			"data": nil,
		})
		return
	}
	token, err := gojwt.NewJWT(consts.Jwt_KFY).CreateToken(gojwt.CustomClaims{
		ID: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() * 3600 * 24 * 7,
		},
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": token,
	})

}

func RefreshJwt(c *gin.Context) {
	token, err := gojwt.NewJWT(consts.Jwt_KFY).RefreshToken(c.Request.Header.Get("x-token"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "生成token失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "ok",
		"data": token,
	})
	return
}
